package com.ruoyi.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.ExamPaperTitleItemObject;
import com.ruoyi.system.domain.SysExamPaper;
import com.ruoyi.system.domain.SysQuestion;
import com.ruoyi.system.mapper.SysExamPaperMapper;
import com.ruoyi.system.service.ISysExamPaperService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 试卷信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-17
 */
@Service
@RequiredArgsConstructor
public class SysExamPaperServiceImpl extends ServiceImpl<SysExamPaperMapper, SysExamPaper> implements ISysExamPaperService {
    private final SysExamPaperMapper sysExamPaperMapper;

    @Override
    public int insert(SysExamPaper sysExamPaper) {
        setQuestionCount(sysExamPaper);
        return sysExamPaperMapper.insert(sysExamPaper);
    }

    @Override
    public int update(SysExamPaper sysExamPaper) {
        setQuestionCount(sysExamPaper);
        return sysExamPaperMapper.updateById(sysExamPaper);
    }

    @Override
    public SysExamPaper selectInfoById(Long id) {
        SysExamPaper sysExamPaper = sysExamPaperMapper.selectInfoById(id);
        List<ExamPaperTitleItemObject> itemObjects = getFrameTextContent(sysExamPaper.getFrameTextContent());
        List<SysQuestion> allQuestionItems = itemObjects.stream()
                .filter(Objects::nonNull)
                .map(ExamPaperTitleItemObject::getQuestionItems)
                .filter(Objects::nonNull)
                .flatMap(List::stream)
                .collect(Collectors.toList());
        sysExamPaper.setQuestions(allQuestionItems);
        return sysExamPaper;
    }

    @Override
    public List<SysExamPaper> selectSysExamPaperList(SysExamPaper sysExamPaper) {
        return sysExamPaperMapper.selectSysExamPaperList(sysExamPaper);
    }


    public void setQuestionCount(SysExamPaper sysExamPaper) {
        Long totalQuestionCount = sysExamPaper.getFrameTextContent()
                .stream()
                .mapToLong(ExamPaperTitleItemObject::getQuestionCount)
                .sum();
        Long totalScore = sysExamPaper.getFrameTextContent()
                .stream()
                .mapToLong(ExamPaperTitleItemObject::getScore)
                .sum();
        sysExamPaper.setScore(totalScore);
        sysExamPaper.setQuestionCount(totalQuestionCount);

    }

    public List<ExamPaperTitleItemObject> getFrameTextContent(List<ExamPaperTitleItemObject> objects) {
        List<ExamPaperTitleItemObject> list = new ArrayList<>();
        for (Object object : objects) {
            ExamPaperTitleItemObject bean = JSONUtil.toBean(JSONUtil.toJsonStr(object), ExamPaperTitleItemObject.class);
            list.add(bean);
        }
        return list;
    }
}
